package com.leyou.controller;

import com.leyou.common.auth.entity.UserInfo;
import com.leyou.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: guojy
 * @date: 2020/3/18 10:22
 * @Description: TODO 用户登录授权
 * 1、用户携带用户名密码，发请求，到授权中心
 * 2、授权中心，查询该用户的信息
 * 3、如果用户存在，授权中心生成 token，否则返回错误信息
 * 4、成功之后，将token返回给用户，存入cookie
 * 5、再其他请求的时候就从cookie中 取出 数据，进行鉴权
 * @version: 1.0
 */
@RestController
public class AuthController {

    @Autowired
    private AuthService authService;

    /**
     * 登录验证 ---》 登录授权
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("login")
    public ResponseEntity<Void> login(@RequestParam("username") String username,
                                      @RequestParam("password") String password,
                                      HttpServletResponse response) {
        authService.login(username, password, response);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 用户鉴权
     *
     * @param request
     * @param response
     * @return
     */
    @GetMapping("verify")
    public ResponseEntity<UserInfo> login(HttpServletRequest request,
                                          HttpServletResponse response) {

        UserInfo userInfo = authService.verify(request, response);
        return ResponseEntity.ok(userInfo);
    }

    /**
     * 退出登录
     */
    @PostMapping("logout")
    public ResponseEntity<Void> logout(HttpServletRequest request, HttpServletResponse response){
        authService.logout(request, response);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }
}
